package api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"lib/http"
	"lib/structs/tables"
	"strings"
	"time"
	"vap/dao"
	"vap/service"
)

var SettingsApi = new(settingsApi)

type settingsApi struct {
}

func (a settingsApi) CreateWinRdpAccount(c *gin.Context) {
	in := struct {
		Accounts []string `json:"accounts"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	service.SettingsService.CreateWinRdpAccount(in.Accounts)
	http.OK204(c)
}

func (a settingsApi) GetWatermarkContext(c *gin.Context) {
	m, err := dao.SettingsRepository.FindWatermark()
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	params := struct {
		BaseContent   string `json:"baseContent"`
		CustomContent string `json:"customContent"`
		Color         string `json:"color"`
		Size          int    `json:"size"`
		GlobalAlpha   int    `json:"globalAlpha"`
	}{}
	err = json.Unmarshal([]byte(m.Value), &params)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	ss := strings.Split(params.BaseContent, ",")
	self := http.GetCurrentUser(c)
	var context string
	for _, item := range ss {
		switch item {
		case "username":
			context += fmt.Sprintf("-%s-", self.Username)
		case "nickname":
			context += fmt.Sprintf("%s-", self.Nickname)
		case "timeNow":
			context += fmt.Sprintf("%s-", time.Now().Format("2006-01-02 15:04:05"))
		case "sessionId":
			context += fmt.Sprintf("%s-", "id")
		}
	}
	context += fmt.Sprintf("%s-", params.CustomContent)
	context = strings.TrimPrefix(context, "-")
	context = strings.TrimSuffix(context, "-")
	http.Ok(c, context)
}

func (a settingsApi) FindWatermark(c *gin.Context) {
	m, err := dao.SettingsRepository.FindWatermark()
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.Ok(c, m.Value)
}

func (a settingsApi) SaveWatermark(c *gin.Context) {
	in := struct {
		Value string `json:"value"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	if err := dao.SettingsRepository.SaveWatermark(in.Value); err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.OK204(c)
}

func (a settingsApi) FindGuaProperties(c *gin.Context) {
	li, err := dao.SettingsRepository.FindGuaProperties()
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.Ok(c, li)
}

func (a settingsApi) UpdateGuaProperty(c *gin.Context) {
	var in tables.GuaProperty
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := dao.SettingsRepository.UpdateGuaProperty(in)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.OK204(c)
}
